package com.luoxiang.socialandroid.activity;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.ACCID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.GENDER;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.HOSTAUDIT;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.IMTOKEN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_PHONE;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.USERID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.USER_NAME;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.WXPAY;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.base.BaseActivity;
import com.luoxiang.socialandroid.bean.LoginBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.SendcodeBean;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.luoxiang.socialandroid.utils.ThendTimeUtil;
import com.luoxiang.socialandroid.view.CustomerCodeView;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 输入验证码界面
 */
public class EnterCodeActivity extends BaseActivity implements CustomerCodeView.InputCompleteListener {
    private TextView tvSecond, tv_tv;
    private TextView phoneNum;
    private ImageView icon_back;
    private CustomerCodeView editText;
    private  String etphone;
    @Override
    protected void initListener() {
        ThendTime();
        if (tvSecond.equals("")) {
            tvSecond.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
        phoneNum.setText(getString(R.string.mi_yanzhengmayifasongzhi) + etphone);
        icon_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }


    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_enter_code);
        setStatusBarTranslucent();

    }

    @Override
    protected void initView() {
        tvSecond = findViewById(R.id.tv_second);
        phoneNum = findViewById(R.id.phone_num);
        tv_tv = findViewById(R.id.tv_tv);
        Intent intent = getIntent();
        etphone = intent.getStringExtra("etphone");

        icon_back = findViewById(R.id.icon_back);
        editText = (CustomerCodeView) findViewById(R.id.edit_code);
        editText.setInputCompleteListener(this);

        showSoftInputFromWindow(EnterCodeActivity.this, editText.getEditText());
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        //显示软键盘
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    private void ThendTime() {
        ThendTimeUtil.Therd(60, new ThendTimeUtil.timeBack() {
            @Override
            public void back(int time, boolean n) {
                if (n) {
                    tvSecond.setText("");
                    tv_tv.setOnClickListener(new CustomClickListener() {
                        @Override
                        protected void onSingleClick() {
                            getLoginbycode(etphone, "login");
                        }

                        @Override
                        protected void onFastClick() {

                        }
                    });
                } else {
                    tvSecond.setText(time + "(S)");
                }
            }
        });
    }

    /**
     * 获取验证码的方法
     *
     * @param phone
     * @param op
     */
    private void getLoginbycode(String phone, String op) {
        NetUtils2.getInstance().getApiService().getsendCode(phone, op, "")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr", decryptStr);
                        Gson gson = new Gson();
                        SendcodeBean sendcodeBean = gson.fromJson(decryptStr, SendcodeBean.class);
                        if (sendcodeBean != null) {
                            int code = sendcodeBean.getCode();
                            LogUtils.i("code", code);
                            if (code == 0) {
                                //跳转
                                ToastUtils.showShort(R.string.mi_yanzhengmahuoquchenggong);
                                ThendTime();
                            } else {
                                ToastUtils.showShort(sendcodeBean.getMsg());
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {
                        clearLoading();
                    }
                });

    }


    @Override
    public void inputComplete() {
        showLoading();
        //当验证码输入4位后调用此方法
        String editContent = editText.getEditContent();
        getloginbycode(0, etphone, editContent, EXTRA);

    }

    @Override
    public void deleteContent(boolean isDelete) {

    }

    private void getloginbycode(Integer type, String thirdId, String code, String extra) {
        NetUtils2.getInstance().getApiService().getloginbycode(type, thirdId,null,null,null, code, extra)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr8699", decryptStr);
                        Gson gson = new Gson();
                        LoginBean loginbean = gson.fromJson(decryptStr, LoginBean.class);
                        if (loginbean != null) {
                            if (loginbean.getData() != null) {
                                if (loginbean.getData().getUser() != null) {
                                    MmkvUtil.INSTANCE.encode(TOKEN, loginbean.getData().getUser().getToken());
                                    MmkvUtil.INSTANCE.encode(ACCID, loginbean.getData().getUser().getId());
                                    MmkvUtil.INSTANCE.encode(WXPAY, loginbean.getData().getUser().getWxPay());
                                    MmkvUtil.INSTANCE.encode(HOSTAUDIT, loginbean.getData().getUser().getHost());
                                    MmkvUtil.INSTANCE.encode(GENDER,loginbean.getData().getUser().getGender());
                                }
                            }
                        }

                        if (loginbean != null) {
                            if (loginbean != null) {
                                if (loginbean.getData() != null) {
                                    MmkvUtil.INSTANCE.encode("phone", loginbean.getData().getThirdId());
                                }
                            }
                            if (loginbean.getCode() == 0) {
                                if (loginbean.getData().getUser() != null) {
                                    MmkvUtil.INSTANCE.encode(USERID, loginbean.getData().getUser().getId());
                                    MmkvUtil.INSTANCE.encode(ACCID, loginbean.getData().getUser().getId());
                                    MmkvUtil.INSTANCE.encode(USER_NAME, loginbean.getData().getUser().getName());
                                    MmkvUtil.INSTANCE.encode("keybutezhi", "ok");
                                    MmkvUtil.INSTANCE.encode(IMTOKEN, loginbean.getData().getUser().getImToken());
                                    MmkvUtil.INSTANCE.encode(ACCID, loginbean.getData().getUser().getId());
                                    Intent intent = new Intent(EnterCodeActivity.this, HomeActivity.class);
                                    startActivity(intent);
                                    try {
                                        LoginActivity.logininstance.finish();
                                    } catch (Exception ignored) {
                                    }
                                    finish();
                                } else {
                                    Intent intent = new Intent(EnterCodeActivity.this, RegisterActivity.class);
                                    startActivity(intent);

                                    try {
                                    } catch (Exception ignored) {
                                    }
                                    finish();
                                }

                            } else {
                                ToastUtils.showShort(loginbean.getMsg());

                            }
                        }
                        clearLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void EnterLogin() {
        NetUtils.getInstance().getApiService();
    }
}